package com.shop.model.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.shop.model.entity.GoodsTb;
import com.shop.model.entity.ShippingAddressTb;
import com.shop.model.service.IGoodsTbService;
import com.shop.model.service.IShippingAddressTbService;
import org.springframework.ui.Model;
import com.shop.model.entity.OrderTb;
import com.shop.model.entity.ShopcartTb;
import com.shop.model.service.IOrderTbService;
import com.shop.model.service.IShopcartTbService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.stereotype.Controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author shop
 * @since 2018-12-19
 */
@Controller

public class OrderTbController {
    @Autowired
    private IOrderTbService iOrderTbService;
    @Autowired
    private IShopcartTbService iShopcartTbService;
    @Autowired
    private IShippingAddressTbService iShippingAddressTbService;
    @Autowired
    private IGoodsTbService iGoodsTbService;

    @RequestMapping("/addOrder")
    public void addOrder(HttpServletRequest request){
        //alicontroller传过来了 订单编号集orderNums  订单描述集description  订单集ids  所属用户userId 价格集prices  商品数量集cartGoodsNums 来源place
        String orderNums = request.getParameter("orderNums");//;分隔的多个订单编号
        String description = request.getParameter("description");//；分隔的多个商品描述
        String ids = request.getParameter("ids");//，分隔的多个商品
        String prices = request.getParameter("prices");//；分隔的多个商品价格集
        String cartGoodsNums = request.getParameter("cartGoodsNums");//；分隔的多个商品数量集合
        int userId1 =Integer.valueOf(request.getParameter("userId"));
        //切
        String[] splitOrderNums = orderNums.split(";");//注意  这样切最后会多个""出来，之前拼接的时候最后一个；没有处理
        int length = splitOrderNums.length;
        String[] splitDescriptions = description.split(";");
        String[] splitIds= ids.split(",");
        String[] splitPrices = prices.split(";");
        String[] splitCartGoodsNums = cartGoodsNums.split(";");
        //由于前面拼接的时候是一一对应的，所以每个字符串拆分后的数组长度是一样的
        //这里需要补 订单创建时间
        //订单流程 1未付款2 已付款3未发货4已发货5未收货6已收货 orderProcess
        //订单状态 1运行中  2已终止  3已完成 orderStatus
        for(int i=0;i<length;i++){
            //创建一个订单
            OrderTb orderTb =new OrderTb();
            orderTb.setPlaceOrderDatetime(LocalDateTime.now());
            orderTb.setOrderUserId(userId1);
            orderTb.setOrderContent(splitDescriptions[i]);
            orderTb.setOrderGoodsId(Integer.valueOf(splitIds[i]));
            orderTb.setOrderNum(splitOrderNums[i]);
            orderTb.setOrderProcess("3");
            orderTb.setOrderStatus("1");
            orderTb.setOrderGoodsNum(Integer.valueOf(splitCartGoodsNums[i]));
            orderTb.setOrderPrice(new BigDecimal(splitPrices[i]));
            //收货地址
            ShippingAddressTb shippingAddressTb = iShippingAddressTbService.getOne(new QueryWrapper<ShippingAddressTb>()
                    .eq("shipping_address_user_id", userId1)
                    .eq("shipping_address_whether_user", 1));
            String shippingAddress = shippingAddressTb.getShippingAddress();
            orderTb.setOrderShippingAddress(shippingAddress);
            //添加订单

            boolean save = iOrderTbService.save(orderTb);
            //支付

        }


        if(request.getParameter("place").equals("shopCart")){
            //说明数据是重购物车传过来的，加入订单后需要清除对应购物车
            String[] idss = ids.split(",");
            for (String s : idss) {
                Integer shopCartId = Integer.valueOf(s);
                //通过这个id去删除购物车
                boolean delete_shopcart_id = iShopcartTbService.remove(new QueryWrapper<ShopcartTb>()
                        .eq("shopcart_id", shopCartId));

            }
        }
        System.out.println("------来订单了------");
    }

    @RequestMapping("/showOrder")
    public String showOrder(HttpServletRequest request, Model model){
        //获取当前用户
        HttpSession session = request.getSession();
        //需要传多个list  总的list  待发货list  已发货list  待收货list  已收货list
        if(null!=session.getAttribute("userId")){
            int userId = (int)session.getAttribute("userId");
            //该用户所有订单
            List<OrderTb> orderListSum = iOrderTbService.list(new QueryWrapper<OrderTb>()
                    .eq("order_user_id", userId));
            System.out.println("-----------所有订单长度="+orderListSum.size());
            HashMap<OrderTb,GoodsTb> sumHashMap=new HashMap<>();//订单是key是因为订单不会重复（订单编号永远不一样）
            for (OrderTb orderTb : orderListSum) {
                String orderProcess = orderTb.getOrderProcess();
                orderTb.setOrderProcess(change(orderProcess));
                Integer orderGoodsId = orderTb.getOrderGoodsId();
                GoodsTb order_user_id = iGoodsTbService.getOne(new QueryWrapper<GoodsTb>()
                        .eq("goods_id", orderGoodsId));
                sumHashMap.put(orderTb,order_user_id);
            }
            System.out.println("-----------所有订单map长度="+sumHashMap.size());
            model.addAttribute("sumHashMap",sumHashMap);
            //该用户待发货的订单waitDeliveredList
            List<OrderTb> waitDeliveredList = iOrderTbService.list(new QueryWrapper<OrderTb>().eq("order_user_id", userId).eq("order_process", 3));
            HashMap<OrderTb,GoodsTb> waitDeliveredHashMap=new HashMap<>();//订单是key是因为订单不会重复（订单编号永远不一样）
            for (OrderTb orderTb1 : waitDeliveredList) {
                String orderProcess = orderTb1.getOrderProcess();
                orderTb1.setOrderProcess(change(orderProcess));
                Integer orderGoodsId = orderTb1.getOrderGoodsId();
                GoodsTb order_user_id1 = iGoodsTbService.getOne(new QueryWrapper<GoodsTb>()
                        .eq("goods_id", orderGoodsId));
                waitDeliveredHashMap.put(orderTb1,order_user_id1);
            }
            model.addAttribute("waitDeliveredHashMap",waitDeliveredHashMap);
            //该用户已发货的订单 alreadyDeliveredList
            List<OrderTb> alreadyDeliveredList = iOrderTbService.list(new QueryWrapper<OrderTb>().eq("order_user_id", userId).eq("order_process", 4));
            HashMap<OrderTb,GoodsTb> alreadyDeliveredHashMap=new HashMap<>();//订单是key是因为订单不会重复（订单编号永远不一样）
            for (OrderTb orderTb2 : alreadyDeliveredList) {
                String orderProcess = orderTb2.getOrderProcess();
                orderTb2.setOrderProcess(change(orderProcess));
                Integer orderGoodsId = orderTb2.getOrderGoodsId();
                GoodsTb order_user_id2 = iGoodsTbService.getOne(new QueryWrapper<GoodsTb>()
                        .eq("goods_id", orderGoodsId));
                alreadyDeliveredHashMap.put(orderTb2,order_user_id2);
            }
            model.addAttribute("alreadyDeliveredHashMap",alreadyDeliveredHashMap);
            //该用户待收货的订单waitReceiptList
            List<OrderTb> waitReceiptList = iOrderTbService.list(new QueryWrapper<OrderTb>().eq("order_user_id", userId).eq("order_process", 5));
            HashMap<OrderTb,GoodsTb> waitReceiptHashMap=new HashMap<>();//订单是key是因为订单不会重复（订单编号永远不一样）
            for (OrderTb orderTb3 : waitReceiptList) {
                String orderProcess = orderTb3.getOrderProcess();
                orderTb3.setOrderProcess(change(orderProcess));
                Integer orderGoodsId = orderTb3.getOrderGoodsId();
                GoodsTb order_user_id3 = iGoodsTbService.getOne(new QueryWrapper<GoodsTb>()
                        .eq("goods_id", orderGoodsId));
                waitReceiptHashMap.put(orderTb3,order_user_id3);
            }
            model.addAttribute("waitReceiptHashMap",waitReceiptHashMap);
            //该用户已收货的订单alreadyReceiptList
            List<OrderTb> alreadyReceiptList = iOrderTbService.list(new QueryWrapper<OrderTb>().eq("order_user_id", userId).eq("order_process", 6));
            HashMap<OrderTb,GoodsTb> alreadyReceiptHashMap=new HashMap<>();//订单是key是因为订单不会重复（订单编号永远不一样）
            for (OrderTb orderTb4 : alreadyReceiptList) {
                String orderProcess = orderTb4.getOrderProcess();
                orderTb4.setOrderProcess(change(orderProcess));
                Integer orderGoodsId = orderTb4.getOrderGoodsId();
                GoodsTb order_user_id4 = iGoodsTbService.getOne(new QueryWrapper<GoodsTb>()
                        .eq("goods_id", orderGoodsId));
                alreadyReceiptHashMap.put(orderTb4,order_user_id4);
            }
            model.addAttribute("alreadyReceiptHashMap",alreadyReceiptHashMap);


            model.addAttribute("username",1);
            //显示商品
            return "order1";
        }
        model.addAttribute("username",0);//提示没登录
        return "order1";
    }

    private String change(String orderProcess) {
        switch (orderProcess){
            case "1":
                return "未付款";
            case "2":
                return "已付款";
            case "3":
                return "未发货";
            case "4":
                return "已付款";
            case "5":
                return "未收货";
            case "6":
                return "已收货";
        }
        return null;
    }
}

